package org.icnmasjid.member.webapp.action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.icnmasjid.member.model.Person;
import org.icnmasjid.member.model.PersonSubOrgRole;
import org.icnmasjid.member.model.Role;
import org.icnmasjid.member.model.SubOrg;
import org.icnmasjid.member.service.PersonManager;
import org.icnmasjid.member.service.impl.BaseManager;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;

public class BasePersonFormController extends BaseFormController {

	protected PersonManager personManager = null;
	protected ModelAndView deleteRole(HttpServletRequest request, HttpServletResponse response, Person person) {
		String personSubOrgRoleId = request.getParameter("personSubOrgRoleId");
		PersonSubOrgRole psr = (PersonSubOrgRole)getManager().getObject(PersonSubOrgRole.class, Integer.valueOf(personSubOrgRoleId));
		person.getPersonSubOrgRoles().remove(psr);
		personManager.savePerson(person);
		Map map = new HashMap();
		map.put("person", person);
		map.put("personSubOrgRoles", person.getPersonSubOrgRoles());
		return new ModelAndView("ajax_personRole", map);
	}

	protected ModelAndView addRole(HttpServletRequest request, HttpServletResponse response, Person person) {
		// get the subOrg id and get the role id
		String subOrgId = request.getParameter("subOrgId");
		String roleId = request.getParameter("roleId");
		PersonSubOrgRole psr = new PersonSubOrgRole();
		psr.setPerson(person);
		psr.setSubOrg((SubOrg)getManager().getObject(SubOrg.class, Integer.valueOf(subOrgId)));
		psr.setRole((Role)getManager().getObject(Role.class, Long.valueOf(roleId)));
		person.getPersonSubOrgRoles().add(psr);
		personManager.savePerson(person);
		Map map = new HashMap();
		map.put("person", person);
		map.put("personSubOrgRoles", person.getPersonSubOrgRoles());
		return new ModelAndView("ajax_personRole", map);
	}

	@Override
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
    	Map map = super.referenceData(request, command, errors);
    	if ( map == null ) {
    		map = new HashMap();
    	}
    	Person p = (Person)command;
    	map.put("personSubOrgRoles", p.getPersonSubOrgRoles());
    	map.put("personPayments", p.getPersonPayments());
    	map.put("personPaymentsList", p.getPersonPaymentsList());
    	return map;
	}

	public void setPersonManager(PersonManager personManager) {
	    this.personManager = personManager;
	}

	public PersonManager getPersonManager() {
		return personManager;
	}

}
